<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="grid-content">
          <h3>部门树形结构</h3>
          <el-tree :data="data" :props="defaultProps" highlight-current @node-click="handleNodeClick"></el-tree>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="grid-content">
          <d2-crud
            ref="d2Crud"
            :columns="columns"
            :data="dataTable"
            :options="options"
            index-row
            :rowHandle="rowHandle"
            @add-model ="addDept"
            @edit-model="editDept"
            @del-model="delDept"
            @current-change="handleCurrentChange">
          </d2-crud>
        </div>
      </el-col>
    </el-row>
    <edit-form
      :dept="dept"
      v-model="editFormVisible"
      @submit="getTableData"
    />
    <add-form
      v-model="addFormVisible"
      :pid="parentID"
      ref="detailFrom"
      @submit="getTableData">
    </add-form>
  </d2-container>
</template>
<script>
import deptApi from "@/api/system/dept";
import roleApi from "@/api/system/role";
import utils from '@/assets/utils/zhzf-util';
import editForm from "./editForm";
import addForm from './addForm';
export default {
  name: "deptPage",
  components: { editForm,addForm},
  data() {
    return {
      columns: [
        {
          title: '部门名称',
          key: 'name',
          width: '180'
        },
        // {
        //   title: '父级id',
        //   key: 'pid',
        //   width: '180'
        // },
        {
          title: '备注',
          key: 'note'
        },
      ],
      data:[],
      dataTable:[],
      newdata:'',
      options:{
        stripe: true,
        highlightCurrentRow: true
      },
      rowHandle: {
        columnHeader:'操作',
          custom: [
            {title: '新增',size: 'mini', emit: 'add-model',icon:"fa fa-plus",style:"color:#409eff;"},
            {title: '修改',size: 'mini', emit: 'edit-model',icon:"el-icon-edit",style:"color:#67c23a;"},
            {title: '删除', size: 'mini', emit: 'del-model',icon:"el-icon-delete",style:"color:#f56c6c;"}
          ]
      },
      currentId:null,
      editFormVisible: false,
      dept:{},
      addFormVisible:false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      parentID:null
    };
  },
  mounted() {
    this.getTableData();
  },
  methods: {
     getTableData() {
        deptApi.deptPage().then(res => {
          console.log(1111,res)
          let treeList = utils.generatorDeptTree(res.data);
          this.data = treeList.treeList
          // this.data = this.initdata
          this.dataTable = res.data;

          roleApi.delDeptRole().then(res => {
           console.log('部门角色',res.data)
          });

        });

      },
    handleNodeClick(data) {
      this.currentNode = data.id;
      console.log(this.currentNode);
    },
    addDept(row){
      console.log('新增',row)
      this.parentID = row.row;
      console.log(this.parentID)
      this.addFormVisible = true;
      this.$refs.detailFrom.getTableData(this.data);
    },
    handleCurrentChange (currentRow) {
       if(currentRow){
         this.currentId = currentRow.id;
       }
    },
  translateDataToTree(data) {
    let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null)
    let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null)
    let translator = (parents, children) => {
      parents.forEach((parent) => {
        children.forEach((current, index) => {
          if (current.parentId === parent.id) {
            let temp = JSON.parse(JSON.stringify(children))
            temp.splice(index, 1)
            translator([current], temp)
            typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
          }
        }
        )
      }
      )
    }
    translator(parents, children)
    return parents
  },

    totree(list) {   //数组转为树形结构数据
      let obj = {};
      let result = [];
      //将数组中数据转为键值对结构 (这里的数组和obj会相互引用)
      list.map(el => {
          obj[el.id] = el;
      })
      for(let i=0, len = list.length; i < len; i++) {
          let id = list[i].parentId;
          if(id == 0) {
              result.push(list[i]);
              continue;
          }
          if(obj[id]&&obj[id].children) {
              obj[id].children.push(list[i]);
          } else {
              obj[id].children = [list[i]];
          }
      }
      console.log(result);
      return result;
    },
    editDept(row){
      console.log(row)
      if(this.currentId){
        for(let i = 0; i < this.data.length; i++){
          if(this.data[i].id == this.currentId){
            this.dept = this.data[i]
          }
        }
        this.editFormVisible = true;

      }
    },
    delDept (row) {
      this.$confirm("确认删除？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消"
      }).then(() => {
        deptApi.delDept({id:row.row.id}).then(() => {
          this.getTableData();
          this.currentId = null;
        });
      });
    },
  }
};
</script>

<style scoped lang="scss">
.el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
</style>
